#include "linklist.h"
#include <stdio.h>
#include <stdlib.h>

linklist link_create()
{
    linklist head = (linklist)malloc(sizeof(linknode));
    if (head == NULL) 
    {
        puts("malloc failed");
        return head;
    }
    head->data = 0;
    head->p_next = NULL;
    return head;
}

linklist list_get(linklist p_head, int pos)
{
    linklist p;
    int i = 0;
    if (p_head == NULL)
    {
        puts("p_head is NULL");
        return p_head;
    }

    if (pos == -1) return p_head;

    p = p_head;
    i = -1;
    while (i < pos)
    {
        p = p->p_next;
        if (p == NULL)
        {
            puts("pos is invalid.\n");
            return NULL;        
        }
        i++;
    }
    
    return p ;
}

int list_insert(linklist p_head, data_t value, int pos)
{
    linklist p, p_new;
    if (NULL == p_head)
    {
        printf("p_head is NULL.\n");
        return -1;
    }

    // 找到要插入位置的前一个节点
    p = list_get(p_head, pos - 1);
    if (NULL == p) return -1;
    // 新建一个节点
    p_new = (linklist)malloc(sizeof(linknode));

    if (NULL == p_new) 
    {
        puts("malloc failed.");
        return -1;
    }
    p_new->data = value;
    // 将新建立的节点插入到链表中
    p_new->p_next = p->p_next;
    p->p_next = p_new;
    
    return 0;
}

int list_tail_insert(linklist head, data_t value)
{
    linklist p_new = (linklist)malloc(sizeof(linknode));
    if (head == NULL)
    {
        printf("head is NULL\n");
        return -1;
    }
    if (NULL == p_new)
    {
        puts("malloc failed.");
        return -1;
    }
    p_new->data = value;
    p_new->p_next = NULL;

    while (head->p_next != NULL) head = head->p_next;
    head->p_next = p_new;

    return 0;
}

int list_show(linklist pHead)
{
    if (pHead == NULL)
    {
        puts("PHead is NULL.");
        return -1;
    }
    while (pHead->p_next != NULL)
    {
        printf("%d ", pHead->p_next->data);
        pHead = pHead->p_next;
    }
    puts("");

    return 0;
}

linklist list_free(linklist p_head)
{
    linklist p;
    if (p_head == NULL)
    {
        puts("p_head is NULL.");
        return NULL;
    }
    
    while (!p_head->p_next)
    {
        p = p_head;
        p_head = p_head->p_next;
        free(p);
    }   
    free(p_head);
    return NULL;
}

int list_delete(linklist p_head, int pos)
{
    linklist p, p_del;
    if (NULL == p_head) 
    {
        puts("p_head is NULL.");
        return -1;
    }

    if (pos < -1)
    {
        puts("pos is invalid.");
        return -1;
    }
    p = list_get(p_head, pos - 1);

    if (p->p_next == NULL)
    {
        puts("pos is invalid.");
        return -1;
    }
    p_del = p->p_next;
    p->p_next = p->p_next->p_next;
    free(p_del);

    return 0;
}